<?php

class LTBDatabase
{
	private static $dbInstance;
	private $dbhost = "localhost";
	private $dbuser = "root";
	private $dbpass = "password";
	private $dbname = "learntobe";
	private $conn;

	private function __construct() {
		$this->conn = mysql_connect($this->dbhost, 
			      		    $this->dbuser, 
					    $this->dbpass) 
		      or die (mysql_error());
		mysql_select_db($this->dbname, $this->conn)
		      or die (mysql_error());
	}

	public static function getInstance() {
	       if (!self::$dbInstance)
	       	  self::$dbInstance = new LTBDatabase();

	       return self::$dbInstance;
	}
}

class QuestionDbWriter
{
	private static $dbInstance;
	public static function getInstance() {
	   if (!self::$dbInstance)
	      self::$dbInstance = new QuestionDbWriter();
	   return self::$dbInstance;
	}

	private function __construct() {
	   LTBDatabase::getInstance();
	}

	public function getDefinitionFromDb($id) {
	   $query = "SELECT * FROM question_definitions WHERE id='$id'";
	   $result = mysql_query($query) or die (mysql_error());
	   if (mysql_num_fields($result) == 0)
	      return false;
	   $row = mysql_fetch_array($result, MYSQL_ASSOC);
	   $dataDf = new QuestionDefinition($row['definition'], 
					    $row['question'], 
					    $row['answer'], 
					    $row['solution'], 
					    $row['solutionFn'], 
					    $row['flags']);
	   $dataDf->templateId = $row['id'];
	   $dataDf->questionDescription = $row['description'];
	   return $dataDf;
       }

	public function getQuestionFromDb($handle) {
	   $query = "SELECT testQuestion FROM active_questions WHERE id='$handle'";
    	   $result = mysql_query($query) or die (mysql_error());
	   if (mysql_num_fields($result) == 0)
	      return false;
	   $row = mysql_fetch_array($result, MYSQL_ASSOC);
	   return unserialize($row['testQuestion']);
	}

	public function storeTestQuestion($input) {
	   $questionId = $input->handle;
	   $data = serialize($input);

	   $query = "INSERT INTO active_questions (id, testQuestion) 
	       	     VALUES ('$questionId', '$data')";
	   mysql_query($query) or die (mysql_error());
	}

	public function removeTestQuestion($question) {
	   $query = "DELETE FROM active_questions WHERE id='".$question->handle."'";
	   mysql_query($query) or die (mysql_error());
	}

	public function updateUserResults($question) {
	   $user = $question->handle;
	   $questionStr = $question->question;
	   $answerStr = $question->answer;
	   $isCorrect = $question->userIsCorrect;
	   $userAnswer = $question->userAnswer;
	   $userTime = $question->userTime;

	   $query = "INSERT INTO question_history (user_id,
						   question,
						   answer,
						   is_correct,
						   user_answer,
						   user_time)
		     VALUES ('$user',
			     '$questionStr',
			     '$answerStr',
			     '$isCorrect',
			     '$userAnswer',
			     '$userTime')";
	   mysql_query($query) or die (mysql_error());
	}
}

class UserResultDbWriter
{
   private static $dbInstance;
   public static function getInstance() {
      if (!self::$dbInstance)
         self::$dbInstance = new UserResultDbWriter();
      return self::$dbInstance;
   }

   private function __construct() {
      LTBDatabase::getInstance();
   }

   public function getUserHistory($userId) {
      $query = "SELECT * FROM question_history WHERE user_id='$userId' ORDER BY question_id DESC LIMIT 10";
      $result = mysql_query($query) or die (mysql_error());
      while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
         $userTestResult = new UserTestResult();
	 $userTestResult->userId = $userId;
	 $userTestResult->questionId = $row['question_id'];
	 $userTestResult->questionStr = $row['question'];
	 $userTestResult->answerStr = $row['answer'];
	 $userTestResult->isCorrect = $row['is_correct'];
	 $userTestResult->userAnswer = $row['user_answer'];
	 $userTestResult->userTime = $row['user_time'];
	 $testResults[] = $userTestResult;
      }
      return $testResults;
   }

   public function getAllStats($userId) {
   	  $numCorrectQuery = "SELECT COUNT(*) FROM question_history WHERE user_id='$userId' AND is_correct='1'";
	  $numTotalQuery = "SELECT COUNT(*) FROM question_history WHERE user_id='$userId'";
	  $totalTimeQuery = "SELECT SUM(user_time) FROM question_history WHERE user_id='$userId'";
	  $correctTimeQuery = "SELECT SUM(user_time) FROM question_history WHERE user_id='$userId' AND is_correct='1'";
	  $result = mysql_query($numCorrectQuery) or die (mysql_error());
	  $row = mysql_fetch_array($result, MYSQL_ASSOC);
	  $numCorrect = $row['COUNT(*)'];

	  $result = mysql_query($numTotalQuery) or die (mysql_error());
	  $row = mysql_fetch_array($result, MYSQL_ASSOC);
	  $numQuestions = $row['COUNT(*)'];

	  $result = mysql_query($totalTimeQuery) or die (mysql_error());
	  $row = mysql_fetch_array($result, MYSQL_ASSOC);
	  $totalTime = $row['SUM(user_time)'];

	  $result = mysql_query($correctTimeQuery) or die (mysql_error());
	  $row = mysql_fetch_array($result, MYSQL_ASSOC);
	  $correctTime = $row['SUM(user_time)'];

	  $accuracy = $numCorrect / $numQuestions * 100;
	  $avgTime = $totalTime / $numQuestions;
	  $avgTimeForCorrect = $correctTime / $numCorrect;
	  $avgTimeForIncorrect = ($totalTime - $correctTime) / ($numQuestions - $numCorrect);
	  print "<br>Accuracy: $accuracy% correct<br>Average $avgTime seconds per questions<br>Average $avgTimeForCorrect seconds per correct answer<br>Average $avgTimeForIncorrect seconds per incorrect answer<br>";
   }

   public function getRecentStats($userId) {
   }
}
?>